<template>
  <div class="repair-wrap">
 

    <!-- 顶部操作区 -->
    <div class="tool-bar">
      <el-button type="primary" size="small" icon="el-icon-plus" @click="addDialogVisible = true">
        报事报修登记
      </el-button>  

      <el-form :inline="true" size="small" style="margin-left: auto;">
        <el-form-item style="margin-bottom: 0;">
          <el-input
            v-model="keyword"
            placeholder="请输入姓名/房号/手机号"
            clearable
            style="width: 260px"
            @clear="filterTable"
            @keyup.enter.native="filterTable"
          />
        </el-form-item>
        <el-form-item style="margin-bottom: 0;">
          <el-button type="primary" @click="filterTable">搜索</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 表格 -->
    <el-table
      :data="tableData"
      border
      size="small"
      style="width: 100%"
      header-cell-class-name="table-head"
    >
      <el-table-column label="小区"  min-width="120">
        <template #default="{ row }">{{ row.communityName }}</template>
      </el-table-column>
      <el-table-column label="房间号"  min-width="130">
        <template #default="{ row }">{{ row.repairRoom }}</template>
      </el-table-column>
      <el-table-column label="来源"  min-width="80">
        <template #default="{ row }">{{ sourceText(row.repairSource) }}</template>
      </el-table-column>
      <el-table-column label="联系人"  min-width="100">
        <template #default="{ row }">{{ row.repairContact }}</template>
      </el-table-column>
      <el-table-column label="联系电话"  min-width="130">
        <template #default="{ row }">{{ row.repairPhone }}</template>
      </el-table-column>
      <el-table-column label="状态"  min-width="100">
        <template #default="{ row }">
          <el-tag :type="statusTag(row.repairStatusName)" size="mini">
            {{ row.repairStatusName }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="重要程度"  min-width="90">
        <template #default="{ row }">
          <el-tag :type="priorityTag(row.repairDegreeName)" size="mini">
            {{ row.repairDegreeName }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="受理时间"  min-width="160">
        <template #default="{ row }">{{ row.repairAcceptTime }}</template>
      </el-table-column>
      <el-table-column label="要求完成时间" width="160">
        <template #default="{ row }">{{ row.deadline }}</template>
      </el-table-column>
      <el-table-column label="操作"  min-width="180">
        <template #default="{ row }">
          <el-button type="text" size="mini" @click="handleDetail(row)">详情</el-button>
          <el-button type="text" size="mini" @click="handleEdit(row)">编辑</el-button>
           <el-button type="text" size="mini" @click="openAssignDialog(row)">派单</el-button>
           <el-button type="text" size="mini" @click="openReceiptDialog(row)">回单</el-button>
          <el-button
            type="text"
            size="mini"
            style="color:#f56c6c"
            @click="handleDel(row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 编辑弹窗 -->
    <el-dialog title="编辑报修" :visible.sync="editDialogVisible">
      <el-form :model="editForm" label-width="100px">
        <el-form-item label="房间号">
          <el-input v-model="editForm.repairRoom"></el-input>
        </el-form-item>
        <el-form-item label="联系人">
          <el-input v-model="editForm.repairContact"></el-input>
        </el-form-item>
        <el-form-item label="联系电话">
          <el-input v-model="editForm.repairPhone"></el-input>
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="editForm.repairDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveEdit">保存</el-button>
      </span>
    </el-dialog>

      <!-- 添加报修 Dialog -->
    <el-dialog :visible.sync="addDialogVisible" title="新增报修">
      <el-form :model="addForm" label-width="100px">
        <el-form-item label="小区ID">
          <el-input v-model="addForm.communityId"></el-input>
        </el-form-item>
        <el-form-item label="房间号">
          <el-input v-model="addForm.repairRoom"></el-input>
        </el-form-item>
        <el-form-item label="联系人">
          <el-input v-model="addForm.repairContact"></el-input>
        </el-form-item>
        <el-form-item label="联系电话">
          <el-input v-model="addForm.repairPhone"></el-input>
        </el-form-item>
        <el-form-item label="报修来源">
          <el-select v-model="addForm.repairSource" placeholder="请选择来源">
            <el-option label="上门" :value="0"></el-option>
            <el-option label="电话" :value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="报修描述">
          <el-input type="textarea" v-model="addForm.repairDesc"></el-input>
        </el-form-item>
        <el-form-item label="重要程度">
          <el-select v-model="addForm.repairDegree" placeholder="请选择">
            <el-option label="一般" :value="0"></el-option>
            <el-option label="紧急" :value="1"></el-option>
            <el-option label="严重" :value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="预约时间">
          <el-date-picker v-model="addForm.repairOrderTime" type="date" placeholder="选择日期"></el-date-picker>
        </el-form-item>
        <el-form-item label="要求处理事项">
          <el-input v-model="addForm.repairItem"></el-input>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="addDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitAdd">提交</el-button>
      </template>
    </el-dialog>

<!-- 派单弹窗 -->
    <el-dialog
      title="派单"
      :visible.sync="assignDialogVisible"
      width="400px"
      destroy-on-close
    >
      <el-form
        :model="assignForm"
        ref="assignFormRef"
        label-width="100px"
      >
       
        <el-form-item label="派单人" prop="repairAcceptPerson">
          <el-input v-model="assignForm.repairAcceptPerson" placeholder="请输入派单人" />
        </el-form-item>

        <el-form-item label="派单时间" prop="repairAcceptTime">
          <el-date-picker
            v-model="assignForm.repairAcceptTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择日期"
          />
        </el-form-item>

        <el-form-item label="备注" prop="assignDesc">
          <el-input
            type="textarea"
            v-model="assignForm.assignDesc"
            placeholder="请输入备注"
          />
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="assignDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitAssign">提交</el-button>
      </div>
    </el-dialog>

<!--回单弹窗-->
<el-dialog title="回单" :visible.sync="receiptDialogVisible">
  <el-form ref="receiptFormRef" :model="receiptForm" label-width="80px">
    <el-form-item label="备注">
      <el-input v-model="receiptForm.receiptDesc" placeholder="填写回单备注"></el-input>
    </el-form-item>
  </el-form>
  <span slot="footer" class="dialog-footer">
    <el-button @click="receiptDialogVisible = false">取消</el-button>
    <el-button type="primary" @click="submitReceipt">提交</el-button>
  </span>
</el-dialog>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        background
        layout="total, sizes, prev, pager, next, jumper"
        :page-sizes="[10, 20, 50]"
        :page-size="pageSize"
        :total="total"
        :current-page.sync="currentPage"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script>
import axios from 'axios'

export default {
  name: 'RepairMgmt',
data() {
  return {
    keyword: '',
    tableData: [],
    pageSize: 10,
    currentPage: 1,
    total: 0,
    editDialogVisible: false,
    editForm: {},
    addDialogVisible: false,  // 新增弹窗显示控制
     assignDialogVisible: false, // 派单弹窗显示状态
    addForm: {                // 新增表单数据
      communityId: '',
      repairRoom: '',
      repairContact: '', // 必填
      repairPhone: '',
      repairSource: '',
      repairDesc: '',
      repairDegree: null,
      repairOrderTime: null,
      repairItem: ''
    } ,
   receiptDialogVisible: false,   // 回单弹窗显示
    receiptForm: {                 // ⚠ 一定要在 data() 里初始化
      repairId: '',
      receiptDesc: ''
    },
    assignForm: {
      repairId: '',              // 派单的维修ID
      repairAcceptPerson: '',    // 派单人姓名
      repairAcceptTime: '',      // 派单时间
      assignDesc: '',            // 派单描述
    }// <-- 这里不加逗号即可
    
  }
  
},
created() {
  this.fetchTable()
},
  methods: {
    async fetchTable () {
      try {
        const res = await axios.post('http://localhost:8080/repair/all', {
          page: this.currentPage,
          size: this.pageSize,
          keyword: this.keyword
        })
        if (res.data.code === 200) {
          this.tableData = res.data.data.records
          this.total = res.data.data.total
        }
      } catch (err) {
        console.error(err)
      }
    },

    filterTable () {
      this.currentPage = 1
      this.fetchTable()
    },

    handleSizeChange (val) {
      this.pageSize = val
      this.fetchTable()
    },
    handleCurrentChange (val) {
      this.currentPage = val
      this.fetchTable()
    },
     openReceiptDialog(row) {
    // 把当前行 repairId 传入表单
    this.receiptForm.repairId = row.repairId;
    this.receiptForm.receiptDesc = row.receiptDesc || '';
    this.receiptDialogVisible = true;
  },

    sourceText (value) {
      if (value === 0 || value === '0') return '上门'
      if (value === 1 || value === '1') return '电话'
      return '未知'
    },
    statusTag (status) {
      const map = { '待分派': 'info', '待回单': 'warning', '待回访': 'primary', '已关闭': 'success' }
      return map[status] || ''
    },
    priorityTag (p) {
      return p === '紧急' ? 'danger' : ''
    },

   
    // 详情
    async handleDetail(row) {
  try {
    const res = await axios.get(`http://localhost:8080/repair/detail/${row.repairId}`);
    if (res.data.code === 200) {
      const d = res.data.data;
      // 给 $alert 的 Promise 添加 catch 避免控制台报错
      this.$alert(`
        <p>小区ID：${d.communityId}</p>
        <p>房间号：${d.repairRoom}</p>
        <p>联系人：${d.repairContact}</p>
        <p>联系电话：${d.repairPhone}</p>
        <p>报修来源：${this.sourceText(d.repairSource)}</p>
        <p>描述：${d.repairDesc}</p>
        <p>受理人：${d.repairAcceptPerson || '未分派'}</p>
        <p>受理时间：${d.repairAcceptTime || '-'}</p>
        <p>状态：${d.repairStatusName}</p>
      `, '维修详情', { 
        dangerouslyUseHTMLString: true, 
        confirmButtonText: '关闭' 
      }).catch(() => {}); // <- 捕获用户取消导致的 reject
    }
  } catch (err) {
    this.$message.error('获取详情失败');
  }
},

    // 编辑
    handleEdit(row) {
      this.editForm = { ...row }
      this.editDialogVisible = true
    },
    saveEdit() {
      axios.put('http://localhost:8080/repair/update', this.editForm)
        .then(res => {
          if (res.data.code === 200) {
            this.$message.success('修改成功')
            this.fetchTable()
            this.editDialogVisible = false
          } else {
            this.$message.error(res.data.msg || '修改失败')
          }
        })
        .catch(() => this.$message.error('接口调用失败'))
    },

    // 删除
  handleDel(row) {
  this.$confirm('确定删除该报修记录吗？', '提示', { type: 'warning' })
    .then(() => {
      // 用户点击确定，调用接口
      return axios.delete(`http://localhost:8080/repair/delete/${row.repairId}`)
    })
    .then(res => {
      if (res.data.code === 200) {
        this.$message.success('删除成功')
        this.fetchTable()
      } else {
        this.$message.error(res.data.msg || '删除失败')
      }
    })
    .catch(err => {
      // 用户点击取消，不需要提示
      if (err !== 'cancel') {
        console.error(err)
        this.$message.error('操作失败')
      }
    })
},

submitReceipt() {
  this.$refs.receiptFormRef.validate(valid => {
    if (!valid) return;

    this.$axios.post('http://localhost:8080/repair/receipt', this.receiptForm)
      .then(res => {
        if (res.data.code === 200) {
          this.$message.success('回单成功');
          this.receiptDialogVisible = false;
          this.fetchTable(); // 刷新表格
        } else {
          this.$message.error(res.data.message || '回单失败');
        }
      })
      .catch(() => {
        this.$message.error('网络异常，提交失败');
      });
  });
},
submitAssign() {
  this.$refs.assignFormRef.validate(valid => {
    if (!valid) return;

    this.$axios.post('http://localhost:8080/repair/assign', this.assignForm)
      .then(res => {
        if (res.data.code === 200) {
          this.$message.success('派单成功！');
          this.assignDialogVisible = false;
          this.fetchTable(); // 刷新表格
        } else {
          this.$message.error(res.data.message || '派单失败');
        }
      })
      .catch(() => {
        this.$message.error('网络异常，提交失败');
      });
  });
},

  // 新增
    submitAdd() {
      axios.post('http://localhost:8080/repair/add', this.addForm)
        .then(res => {
          if (res.data.code === 200) {
            this.$message.success('添加成功')
            this.addDialogVisible = false
            this.fetchTable()
            // 清空表单
            this.addForm = {
              communityId: '',
              repairRoom: '',
              repairContact: '',
              repairPhone: '',
              repairSource: null,
              repairDesc: '',
              repairDegree: null,
              
              repairOrderTime: null,
              repairItem: ''
            }
          } else {
            this.$message.error(res.data.msg || '添加失败')
          }
        })
        .catch(() => this.$message.error('接口调用失败'))
        
    }
  }
}
</script>

<style scoped>
.repair-wrap {
  padding: 20px;
  background: #fff;
}
.page-title {
  margin: 0 0 15px 0;
  font-size: 18px;
}
.tool-bar {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}
.pagination {
  margin-top: 15px;
  text-align: right;
}
.table-head {
  background: #f5f7fa !important;
}
</style>
